<script setup>
import Card from "@/components/Card.vue";
import {useStore} from "@/store";
import {User, Message, Select, Refresh} from "@element-plus/icons-vue";
import {computed, reactive, ref} from "vue";
import {post, get,accessHeader} from "@/net";
import {ElMessage} from "element-plus";
import axios from "axios";
// 用户详细信息描述的引用
const desc = ref('');
// 初始化 Vuex store
const store = useStore();
// 计算属性：格式化用户注册时间
const registerTime = computed(() => new Date(store.user.registerTime).toLocaleString());
// 表单引用
const baseFromRef = ref();
const emailFromRef = ref();

// 基本信息表单数据
const baseForm = reactive({
    username: '',
    gender: 1,
    phone: '',
    qq: '',
    wx: '',
    desc: ''
});
// 邮箱验证表单数据
const emailFrom = reactive({
    email: '',
    code: ''
});

// 验证用户名的自定义验证规则
const validateUsername = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入用户名'));
    } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
        callback(new Error('用户名不能包含特殊字符，只能是中文/英文'));
    } else {
        callback();
    }
};

// 表单验证规则
const rules = {
    username: [
        {validator: validateUsername, trigger: ['blur', 'change']},
        {min: 2, max: 8, message: '用户名的长度必须在2-8个字符之间', trigger: ['blur', 'change']},
    ],
    email: [
        {required: true, message: '请输入邮件地址', trigger: 'blur'},
        {type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change']}
    ],
    code: [
        {required: true, message: '请输入获取的验证码', trigger: 'blur'},
    ]
};
// 加载状态管理
const loading = reactive({
    form: true,
    base: false
});

// 保存用户详细信息的函数
const saveDetails = () => {
    baseFromRef.value.validate((isValid) => {
        if (isValid) {
            loading.base = true;
            post('/api/user/save-details', baseForm, () => {
                ElMessage.success('用户信息保存成功');
                store.user.username = baseForm.username;
                desc.value = baseForm.desc;
                loading.base = false;
            }, (message) => {
                ElMessage.warning(message);
                loading.base = false;
            });
        }
    });
};

// 获取用户详细信息并填充表单
get('/api/user/details', data => {
    baseForm.username = store.user.username;
    baseForm.gender = data.gender;
    baseForm.phone = data.phone;
    baseForm.wx = data.wx;
    baseForm.qq = data.qq;
    baseForm.desc = data.desc;
    emailFrom.email = store.user.email;
    loading.form = false;
});

// 验证邮箱的倒计时和有效性状态
const coldTime = ref(0);
const isEmailValid = ref(true);
// 验证邮箱格式和状态更新
const onValidate = (prop, isValid) => {
    if (prop === 'email') isEmailValid.value = isValid;
};

// 发送邮箱验证码的函数
/**
 * 发送邮箱验证码函数
 *
 * 该函数首先验证邮箱输入是否有效如果有效则启动倒计时，并发送验证码到指定邮箱
 * 倒计时结束前，用户无法再次发送验证码，以防止频繁发送导致的邮箱轰炸
 */
function sendEmailCode() {
    // 验证邮箱输入是否有效
    emailFromRef.value.validate((isValid) => {
        // if (isValid) {
        // 设置初始倒计时时间为60秒
        coldTime.value = 60;
        // 发送验证码请求
        get(`/api/auth/ask-code?email=${emailFrom.email}&type=modify`, () => {
            // 验证码发送成功后显示成功消息
            ElMessage.success(`验证码已发送到邮箱: ${emailFrom.email}，请注意查收`);
            // 启动倒计时，每秒减少1
            const handle = setInterval(() => {
                coldTime.value--;
                // 倒计时结束，清除倒计时
                if (coldTime.value === 0) {
                    clearInterval(handle)
                }
            }, 1000)
        }, (message) => {
            // 发送验证码失败后显示警告消息，并重置倒计时
            ElMessage.warning(message);
            coldTime.value = 0;
        })
        // }
    });
}


// 修改用户邮箱的函数
const modifyEmail = () => {
    emailFromRef.value.validate((isValid) => {
        if (isValid) {
            post('/api/user/modify-email', emailFrom, () => {
                ElMessage.success('修改成功，请重新登录');
                store.user.email = emailFrom.email;
                emailFrom.code = '';
            }, (message) => {
                ElMessage.warning(message);
            });
        }
    });
};

function beforeAvatarUpload(rawFile) {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png'){
        ElMessage.error('请上传jpg/png格式的图片');
        return false}
    else if (rawFile.size / 1024 > 100){
        ElMessage.error('图片大小不能超过100kB');
        return false}
    else
        return true;
}

function uploadSuccess(response) {
    ElMessage.success('上传成功');
    store.user.avatar = response.data;
}
</script>

<template>
    <div style="display: flex;max-width: 1200px;margin: 0 auto">
        <div class="settings-left">
            <card v-loading="loading.form" :icon="User" title="账号信息设置"
                  desc="在这里编辑你的个人信息，你可以在隐私设置中选择是否展示这些信息">
                <el-form ref="baseFromRef" :rules="rules" :model="baseForm" label-position="top"
                         style="margin: 0 10px 10px 10px">
                    <el-form-item label="用户名" prop="username">
                        <el-input maxlength="10" v-model="baseForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-radio-group v-model="baseForm.gender">
                            <el-radio :label="0">男</el-radio>
                            <el-radio :label="1">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input maxlength="11" v-model="baseForm.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="qq号" prop="qq">
                        <el-input maxlength="13" v-model="baseForm.qq"></el-input>
                    </el-form-item>
                    <el-form-item label="微信号" prop="wx">
                        <el-input maxlength="20" v-model="baseForm.wx"></el-input>
                    </el-form-item>
                    <el-form-item label="个人简介" prop="desc">
                        <el-input style="font-family: KaiTi;" maxlength="200" v-model="baseForm.desc" type="textarea"
                                  :rows="5"></el-input>
                    </el-form-item>
                </el-form>
                <div>
                    <el-button :loading="loading.base" :icon="Select" @click="saveDetails()"
                               type="success">保存用户信息
                    </el-button>
                </div>
            </card>
            <card style="margin-top: 10px" :icon="Message" title="电子邮件设置" desc="您可以设置更改默认的电子邮箱地址">
                <el-form @validate="onValidate" :rules="rules" ref="emailFromRef" :model="emailFrom"
                         label-position="top"
                         style="margin: 0 10px 10px 10px">
                    <el-form-item label="电子邮箱" prop="email">
                        <el-input v-model="emailFrom.email"></el-input>
                    </el-form-item>
                    <el-form-item prop="code">
                        <el-row style="width: 100%" :gutter="10">
                            <el-col :span="18">
                                <el-input placeholder="请获取验证码" v-model="emailFrom.code"/>
                            </el-col>
                            <el-col :span="6">
                                <el-button @click="sendEmailCode()" :disabled="!isEmailValid ||coldTime > 0"
                                           type="success" style="width: 100%" plain>
                                    {{ coldTime > 0 ? `请稍后${coldTime}秒` : `获取验证码` }}
                                    <!--                  {{coldTime > 0 ? '请稍后 ' + coldTime + ' 秒' : '获取验证码'}}-->
                                </el-button>
                            </el-col>
                        </el-row>
                    </el-form-item>
                </el-form>
                <div>
                    <el-button :icon="Refresh" type="warning" @click="modifyEmail()">更新电子邮件</el-button>
                </div>
            </card>
        </div>

        <div class="settings-right" >
            <div style="position: sticky;top: 20px; ">
                <!--                    添加固定大小-->
                <card>
                    <div style="text-align: center;padding: 5px 15px 0 15px">
                        <el-avatar :size="100"
                                   :src="store.avatarUrl"/>
                        <div style="margin:5px 0">
                            <el-upload
                                :action="axios.defaults.baseURL + '/api/image/avatar'"
                                :show-file-list="false"
                                :before-upload="beforeAvatarUpload"
                                :on-success="uploadSuccess"
                                :headers="accessHeader()">
                                <el-button  type="primary" size="small" round>修改头像</el-button>
                            </el-upload>
                        </div>
                        <div style="font-weight: bold">你好，{{ store.user.username }}</div>
                    </div>
                    <el-divider style="margin: 10px 0"/>
                    <div style="font-family: KaiTi;font-size: 14px;color: grey;padding: 10px">
                        {{ baseForm.desc || "你还没有设置个人简介" }}
                    </div>
                </card>
                <card style="margin-top: 10px;font-size: 14px">
                    <div style="font-family: KaiTi;font-weight: bold">账号注册时间：{{ registerTime }}</div>
                    <div style="font-family: KaiTi;color: grey">欢迎加入我们的学习论坛</div>
                </card>
            </div>
        </div>
    </div>
</template>

<style scoped>
.settings-left {
    flex: 1;
    margin: 20px;
}

.settings-right {
    width: 350px;
    margin: 20px;
}
</style>